<?php

    /**
     * @name 文件操作类
     * @copyright tcsos inc
     * @version cooperation v1.0
     */
    class file{

        //构造函数
        public function __construct(){

        }
        //析构函数
        public function __destruct(){

        }

        /**
         * @declare     上传文件
         * @param       表单名 , 存储路径 , 重命名，重命名名称
         * @return      bool
         */
        public function upload_file($filename , $folder , $maxsize = 0 , $rename = true, $name = ''){
            if($filename == '' || $folder == ''){
                return false;
            }
            //检查文件夹是否存在，并创建
            if(!$this->make_dir($folder)){
                return false;
            }
            //如果上传为空        
            if(!isset($_FILES) || !isset($_FILES[$filename])){
                return false;
            }
            $file = $_FILES[$filename];
            if(!file || empty($file)){
                return false;
            }
            //判断大小
            if($maxsize>0 && $file['size'] > $maxsize){
                return false;
            }
            //获取用户名
            $f_name = $file['name'];
            //文件名是否为空
            if($f_name == ''){
                return false;
            }
            $f_array = $this->get_file_name($f_name);
            $f_array['extend'] = strtolower($f_array['extend']);

            //是否需要重新命名
            if($rename){

                if(!$f_array){
                    return false;
                }
                if(!$name) {
                    $f_name = substr(md5(microtime()), 8, 16).'.'.$f_array['extend'];
                } else {
                    $f_name = "{$name}.{$f_array['extend']}";
                }
            }
            $save_path = str_replace('//','/',$folder.'/'.$f_name);        
            if(!move_uploaded_file($file['tmp_name'],$save_path)){
                return false;
            }
            return array('name'=>$f_name,'extend'=>$f_array['extend'],'size'=>$file['size'],'folder'=>$folder);
        }

        /**
         * @declare     获取文件内容
         * @param       文件名 , 按行读取
         * @return      array() , bool
         */
        public function get_file_content($path , $byline = false){
            if($path == '' || !file_exists($path) || is_dir($path)){
                return false;
            }
            //如果不是按行读取
            if(!$byline){
                return file_get_contents($path);
            }
            //如果是按行读取
            $handle = @fopen($path, "r");
            if(!$handle){
                return false;
            }
            $line_array = array();
            while (!feof($handle)) {
                $line_array[] = fgets($handle, 4096);
            }
            return $line_array;
        }

        /**
         * 获取目录下的所有文件
         * 
         * @param string $dir       目录
         * @param string $files     文件
         */
        public function get_dir_files($dir, &$files) {
            if(is_file($dir)) {
                $files[] = $dir;
                return false;
            }

            $dir_source = opendir($dir);
            while($file = readdir($dir_source)) {
                if($file == '..' || $file == '.' || $file == '.svn') {
                    continue;
                }                
                $this->get_dir_files($dir . '/' . $file, $files);                                    
            }
        }

        /**
         * 写入内容
         * 
         * @author zhouqi 2012-8-16 PM 01:28:03
         * @param string $content   内容
         * @param string $path      地址
         */
        public function write_content($content, $path) {

            //创建目录
            $this->make_dir(dirname($path));

            //写入内容
            file_put_contents($path, $content);
        }

        /**
         * @declare     获取文件名，文件扩展名
         * @param       文件名
         * @return      array() , bool
         */
        public function get_file_name($filename){
            if($filename == ''){
                return false;
            }
            $files = explode('.',$filename);
            $length = count($files);
            if($length < 2){
                return false;
            }
            $name = '';
            for($i = 0 ; $i < ($length-1) ; $i++){
                $name .= $files[$i];
            }
            return array('name'=>$name , 'extend'=>$files[$length-1]);

        }

        /**
         * @declare     按行写入字符文件
         * @param       写入信息, 文件名,文件夹路径
         * @return      bool
         */
        public function wirte_txt_line($message , $filename , $folder){
            if($message == '' || $filename == '' || $folder == ''){
                return false;
            }
            //检查文件夹是否存在，并创建
            if(!$this->make_dir($folder)){
                return false;
            }
            $filepath = str_replace('//','/',$folder.'/'.$filename);
            $handle = fopen($filepath, "a");
            if($handle){
                fwrite($handle,$message."\r\n");
                fclose($handle);
            }
            return true;
        }

        /**
         * @declare     删除文件,或者夹,如果文件夹下有文件也一并删除
         * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
         * @return      bool
         */
        public function del_path($path){
            //如果为空则返回
            if($path == ''){
                return false;
            }
            //如果文件夹不存在
            if(!file_exists($path)){
                return false;
            }
            //如果是文件则删除
            if(!is_dir($path)){
                @unlink($path);
                return true;
            }
            //处理文件夹
            $handle = @opendir($path);
            while(($file = @readdir($handle)) !== false) 
            { 
                if($file == '.' || $file == '..'){
                    continue;
                }
                $c_path = $path.'/'.$file;
                if(is_dir($c_path)){
                    $this->del_path($c_path); //如果是文件夹则递归  
                }else{
                    @unlink($c_path);//如果是文件直接删除
                }
            } 
            closedir($handle);
            return rmdir($path);
        }

        /**
         * @declare     检查目标文件夹是否存在，如果不存在则自动创建该目录
         * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
         * @return      bool
         */
        public function make_dir($folder) {
            $reval = false;
            $exist = file_exists($folder);
            //如果文件夹存在
            if($exist){
                $reval = is_dir($folder);
                return  $reval;
            }
            //如果不存在则开始创建
            @umask(0);
            /* 将目录路径拆分成数组 */
            preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
            /* 如果第一个字符为/则当作物理路径处理 */
            $base = ($atmp[0][0] == '/') ? '/' : '';
            /* 遍历包含路径信息的数组 */
            foreach ($atmp[1] AS $val)
            {
                if($val == ''){
                    continue;
                }
                $base .= $val;
                if ($val == '..' || $val == '.')
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';
                    continue;
                }
                $base .= '/';
                //如果目录存在则继续
                if(file_exists($base)){
                    continue;
                }
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir(rtrim($base, '/'), 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
            clearstatcache();
            return $reval;
        }        

        /**
         * 生成裁剪略缩图
         * 
         * @param mixed $images_path 图片目录
         * @param mixed $photo 图片名称
         * @param mixed $top 裁剪的y
         * @param mixed $left 裁剪的x
         * @param mixed $width 选择裁剪区域宽
         * @param mixed $height 选择裁剪区域高
         * @param mixed $max_width 目标略缩图最宽
         * @param mixed $max_height 目标略缩图最高
         * @param mixed $thumb_postfix 缩略图后缀 默认_thumb 如果空 就是原图
         * @return mixed
         */
        public function image_make_thumb($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix='thumb_',$inc_array=array()){
            //切分文件
            $filename = explode('.', $photo);
            
            //文件后缀
            $extension = array_pop($filename);
            
            //链接文件  
            $thumb = $thumb_postfix . implode('.',$filename)."." . $extension;
            
            return $this->image_make($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix,$inc_array, $thumb);            
        }

        /**
         * 生成裁剪略缩图
         * 
         * @param mixed $images_path 图片目录
         * @param mixed $photo 图片名称
         * @param mixed $top 裁剪的y
         * @param mixed $left 裁剪的x
         * @param mixed $width 选择裁剪区域宽
         * @param mixed $height 选择裁剪区域高
         * @param mixed $max_width 目标略缩图最宽
         * @param mixed $max_height 目标略缩图最高
         * @param mixed $thumb_postfix 缩略图后缀 默认_thumb 如果空 就是原图
         * @return mixed
         */
        public function image_make_thumb_ext($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix='thumb_',$inc_array=array()){
            
            //切分文件
            $filename = explode('.', $photo);
            
            //文件后缀
            $extension = array_pop($filename);

            //链接文件
            $thumb = implode('.',$filename).".{$extension}{$thumb_postfix}." . $extension;
            
            return $this->image_make_thumb_adv($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix,$inc_array, $thumb);            
        }                



        /**
         * 生成裁剪略缩图
         * @author zhufu 2013-04-27 11:08:00
         * 
         * @param mixed $images_path 图片目录
         * @param mixed $photo 图片名称
         * @param mixed $top 裁剪的y
         * @param mixed $left 裁剪的x
         * @param mixed $width 选择裁剪区域宽
         * @param mixed $height 选择裁剪区域高
         * @param mixed $max_width 目标略缩图最宽
         * @param mixed $max_height 目标略缩图最高
         * @param mixed $thumb_postfix 缩略图后缀 默认_thumb 如果空 就是原图
         * @return mixed
         */
        public function image_make_thumb_adv($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix='thumb_',$inc_array=array(), $thumb=false)
        {
            //$images_path = "..\\".get_user_base_dir();  //replace this with the path where your images are stored, relative to the directory this script will run from
            $thumbs_path = $images_path;//this is you destination thumbmail folder, you can change it if you want, just be sure the folder actually exists and is writeable by the web server.  In this example, we don't deal with duplicate names, so we just store the cropped verion in a different folder.

            $quality = $inc_array['quality']?$inc_array['quality']:90; //生成质量
            $fill_margin = isset($inc_array['fill_margin'])?$inc_array['fill_margin']:true; //填充空白处
            $cut_center = isset($inc_array['cut_center'])?$inc_array['cut_center']:true; //居中裁剪


            if(!($photo && is_numeric($top) && is_numeric($left) && is_numeric($width) && is_numeric($height) && is_numeric($max_height) && is_numeric($max_width))){
                return '{"error":"Some of the required parameters are missing."}';
            }

            //we verify the GD library is running.
            if(! extension_loaded('gd')){
                return '{"error":"The GD extension is not installed on the server."}';
            }

            /*
            we are going to suppose that $photo contains the source image file name, which it should if you passed it properly from UvumiCrop in the first place.
            */

            $source_file = $images_path ."/". $photo;

            //we make sure the source path exists
            if(!is_dir($images_path)) {
                return '{"error":"The source directory could not be found."}';
            }
            //we make sure the source file exists
            if(!file_exists($source_file)) {
                return '{"error":"The source image file could not be found."}';
            }

            //try create the target folder if it doesn't exist
            if(!is_dir($thumbs_path)) {
                if(!mkdir($thumbs_path,0777,true)){
                    return '{"error":"The destination directory could not be created."}';
                }
            }

            //Make sure the target folder is writable
            if(!is_writable($thumbs_path)){
                return '{"error":"The server does not have permission to write in the destination folder."}';
            }

            //We get the file extension from the file name. It's needed later
            $filename = explode('.', $photo);
            $extension = array_pop($filename);

            //we create a new filename from the original with the "thumb" suffix.
            if(!$thumb){
                $thumb = $thumb_postfix . implode('.',$filename)."." . $extension;
            }
            


            //the full target path + file name
            $target_file = $thumbs_path ."/". $thumb;

            $info = getimagesize($source_file);

            if(!$info){
                return '{"error":"The file type is not supported."}';
            }

            // we use the the GD library to load the image, using the file extension to choose the right function
            switch($info[2]) {
                case IMAGETYPE_GIF:
                    if(!$source_image = imagecreatefromgif($source_file)){
                        return '{"error":"Could not open GIF file."}';
                    }
                    break;
                case IMAGETYPE_PNG:
                    if(!$source_image = imagecreatefrompng($source_file)){
                        return '{"error":"Could not open PNG file."}';
                    }
                    break;
                case IMAGETYPE_JPEG:
                    if(!$source_image = imagecreatefromjpeg($source_file)){
                        return '{"error":"Could not open JPG file."}';
                    }
                    break;
                case IMAGETYPE_BMP:
                    include_once LIBDIR.'/bmp.php';
                    if(!$source_image = imagecreatefrombmp($source_file)){
                        return '{"error":"Could not open BMP file."}';
                    }
                    break;
                default:
                    return '{"error":"The file type is not supported."}';
                    break;
            }

            //重写目标图的尺寸计算规则
            /**
            * 大图压缩      将图压缩在一个最大宽高内   分为 填充和不填充
            * 图片裁剪      将图按用户的指定裁剪 分为 居中与不居中，也叫是否拉伸    也可分为填充与不填充
            * 
            * $max_width    目标图片的最大宽高
            * $width        资源图片的宽高，默认为原始宽高
            * $dest_width   目标图的有效区域宽高
            * $min_width    资源图的有效区域，如果大于原始宽高，会出现黑框
            * $dest_x       目标图的有效区域的左上角坐标
            * 
            */            
            if($width < 1 || $width > $info[0]){
                //裁剪的宽高小于1，说明裁剪区域为整个图片的宽或高
                $width = $info[0];                        
            }
            if($height < 1 || $height > $info[1]){
                $height = $info[1];
            }
            //最大宽高的比例
            $scale = $max_width / $max_height;
            if($fill_margin){
                //要进行填充，保证生成的图是完整的最大宽高
                if($cut_center){
                    //要进行居中
                    //计算图片的有效宽高                    
                    if($width / $height > $scale){
                        //宽高比大于最大宽高，属于宽图
                        $dest_width = $max_width;
                        $dest_height = round($height / $width * $dest_width);
                    }
                    else{
                        //宽高比小于最大宽高，属于高图
                        $dest_height = $max_height;
                        $dest_width = round($width / $height * $dest_height);
                    }                    
                }
                else{
                    //不居中
                    //计算图片的有效宽高                    
                    if($width < $max_width && $height < $max_height){
                        //原始图在最大宽高范围之内
                        $dest_width = $width;
                        $dest_height = $height;
                    }
                    else{                        
                        if($width / $height > $scale){
                            //宽高比大于最大宽高，属于宽图
                            $dest_width = $max_width;
                            $dest_height = round($height / $width * $dest_width);
                        }else{
                            //宽高比小于最大宽高，属于高图
                            $dest_height = $max_height;
                            $dest_width = round($width / $height * $dest_height);
                        }
                    }      
                }                
                $min_width = $width;    //资源图的宽
                $min_height = $height;  //资源图的高                
                $dest_width_temp = $max_width;
                $dest_height_temp = $max_height;     
                $dest_x = round(($dest_width_temp - $dest_width) / 2);
                $dest_y = round(($dest_height_temp - $dest_height) / 2);
            }else{
                //不进行填充，是在最大宽高范围内的最大等比压缩
                if($cut_center){
                    //要进行居中
                    //计算图片的有效宽高                    
                    if($width / $height > $scale){
                        //宽高比大于最大宽高，属于宽图
                        $dest_width = $max_width;
                        $dest_height = round($height / $width * $dest_width);
                    }
                    else{
                        //宽高比小于最大宽高，属于高图
                        $dest_height = $max_height;
                        $dest_width = round($width / $height * $dest_height);
                    }                    
                }
                else{
                    //不居中
                    //计算图片的有效宽高                    
                    if($width < $max_width && $height < $max_height){
                        //原始图在最大宽高范围之内
                        $dest_width = $width;
                        $dest_height = $height;
                    }
                    else{                        
                        if($width / $height > $scale){
                            //宽高比大于最大宽高，属于宽图
                            $dest_width = $max_width;
                            $dest_height = round($height / $width * $dest_width);
                        }else{
                            //宽高比小于最大宽高，属于高图
                            $dest_height = $max_height;
                            $dest_width = round($width / $height * $dest_height);
                        }
                    }
                }                                                        
                $min_width = $width;    //资源图的宽
                $min_height = $height;  //资源图的高                
                $dest_width_temp = $dest_width;
                $dest_height_temp = $dest_height;      
                $dest_x = 0;
                $dest_y = 0;
            }
            //we generate a new image object of the size calculated above, using PHP's GD functions
            if(!$dest_image = imagecreatetruecolor($dest_width_temp,$dest_height_temp)){
                return '{"error":"Could not create new image from source file."}';
            }

            //set the background color
            $back = imagecolorallocate($dest_image, 255, 255, 255);
            imagefill($dest_image,0,0,$back);
            //hack to keep transparency in gif and png
            if($info[2]==IMAGETYPE_GIF||$info[2]==IMAGETYPE_PNG){
                if($info[2]==IMAGETYPE_PNG){
                    imageAntiAlias($dest_image,true);
                }
                imagecolortransparent($dest_image, imagecolorallocatealpha($dest_image, 0, 0,0,127));
                imagealphablending($dest_image, false);
                imagesavealpha($dest_image, true);
            }
            if(!imagecopyresampled($dest_image, $source_image, $dest_x, $dest_y, $left, $top, $dest_width, $dest_height, max($width, $min_width), max($height, $min_height))){
                return '{"error":"Could not crop the image with the provided coordinates."}';
            }
            switch($info[2]) {
                case IMAGETYPE_GIF:
                    if(!imagegif($dest_image, $target_file)){
                        return '{"error":"Could not save GIF file."}';
                    }
                    break;
                case IMAGETYPE_PNG:
                    if(!imagepng($dest_image, $target_file, max(9 - floor($quality/10),0))){
                        return '{"error":"Could not save PNG file."}';
                    }
                    break;
                case IMAGETYPE_JPEG:
                    if(!imagejpeg($dest_image, $target_file, $quality)){
                        return '{"error":"Could not save JPG file."}';
                    }
                    break;
                case IMAGETYPE_BMP:
                    if(!imagejpeg($dest_image, $target_file, $quality)){
                        return '{"error":"Could not save JPG file."}';
                    }
                    break;
            }
            imagedestroy($dest_image);
            imagedestroy($source_image);
            return '{"success":"'.$thumb.'"}';
        }


        /**
         * PHP图片水印 (水印支持图片或文字)支持中文
         * @param  string    $groundImage    背景图片路径
         * @param  intval    $waterPos       水印位置:有10种状态，1-9以外为随机位置；
         *                                      1为顶端居左，2为顶端居中，3为顶端居右；
         *                                      4为中部居左，5为中部居中，6为中部居右；
         *                                      7为底端居左，8为底端居中，9为底端居右；
         * @param  array     $water_arr      参数数组，可包含如下值：
         *----------------------------------------------------------------
         *   string    $type       添加水印的类型 ,  'img' => 添加水印图片, 'text' => 添加水印文字,
         *   string    $path       添加水印图片时,水印图片的路径,
         *   string    $content    添加水印文字的文字内容
         *   string    $textColor  添加水印文字的文字颜色
         *   string    $textFont   添加水印文字的文字小大
         *   string    $textFile   添加水印文字的文字字库路径
         *----------------------------------------------------------------
         * @return mixed    返回TRUE或错误信息，只有当返回TRUE时，操作才是成功的
         * @example
         * <code>
         * imageWaterMark('./apntc.gif', 1,  array('type' => 'img', 'path')); 添加水印图片
         * imageWaterMark('./apntc.gif', 1, array('type' => 'text', 'content' => '', 'textColor' => '', 'textFont' => ''));  添加水印文字
         * </code>
         */
        public function image_water_mark($backgroundPath, $waterPos = 9, $water_arr = array('type' => 'img', 'path' => 'static/watermark.png'))
        {
            $isWaterImage = FALSE;
            //读取背景图片
            if(!empty($backgroundPath) && file_exists($backgroundPath)){
                $background_info = getimagesize($backgroundPath);
                $ground_width = $background_info[0];//取得背景图片的宽
                $ground_height = $background_info[1];//取得背景图片的高

                switch($background_info[2])//取得背景图片的格式
                {
                    case 1:
                        $background_im = imagecreatefromgif($backgroundPath);break;
                    case 2:
                        $background_im = imagecreatefromjpeg($backgroundPath);break;
                    case 3:
                        $background_im = imagecreatefrompng($backgroundPath);break;
                    default:
                        die($formatMsg);
                }
            } else {
                return 'water image is not exists';
            }
            //设定图像的混色模式
            imagealphablending($background_im, true);

            if (is_array($water_arr) && !empty($water_arr)) {
                if($water_arr['type'] === 'img' && !empty($water_arr['path']) && file_exists($water_arr['path'])){
                    $isWaterImage = TRUE;
                    $set = 0;
                    $offset = isset($water_arr['offset']) && !empty($water_arr['offset']) ? $water_arr['offset'] : 0;
                    $water_info = getimagesize($water_arr['path']);
                    $water_width = $water_info[0];//取得水印图片的宽
                    $water_height = $water_info[1];//取得水印图片的高
                    switch($water_info[2])//取得水印图片的格式
                    {
                        case 1:
                            $water_im = imagecreatefromgif($water_arr['path']);
                            break;
                        case 2:
                            $water_im = imagecreatefromjpeg($water_arr['path'])
                            ;break;
                        case 3:
                            $water_im = imagecreatefrompng($water_arr['path']);
                            break;
                        default:
                            return 'picture format mistake';
                    } 
                } elseif ($water_arr['type'] === 'text' && $water_arr['content'] !='') {
                    $fontfile =  isset($water_arr['fontFile']) && !empty($water_arr['fontFile']) ?  $water_arr['fontFile'] : 'simkai.ttf';
                    $fontfile = 'C:\WINDOWS\Fonts\\' . $fontfile ;
                    $waterText = $water_arr['content'];
                    $set = 1;
                    $offset = isset($water_arr['offset']) && !empty($water_arr['offset']) ? $water_arr['offset'] : 5;
                    $textColor =  !isset($water_arr['textColor']) || empty($water_arr['textColor']) ? '#FF0000' :  $water_arr['textColor']; 
                    $textFont =  !isset($water_arr['textFont']) || empty($water_arr['textFont']) ? 20 :  $water_arr['textFont']; 
                    $temp = @imagettfbbox(ceil($textFont),0,$fontfile,$waterText);//取得使用 TrueType 字体的文本的范围
                    $water_width = $temp[2] - $temp[6];
                    $water_height = $temp[3] - $temp[7];
                    unset($temp);
                } else {
                    return 'parameter mistake';
                }
            } else {
                return FALSE;
            }

            if( ($ground_width< $water_width) || ($ground_height<$water_height) ) {
                return "water image larger than background image";
            }

            switch($waterPos)
            {
                case 1://1为顶端居左
                    $posX = $offset * $set; 
                    $posY = ($water_height + $offset) * $set;
                    break;
                case 2://2为顶端居中
                    $posX = ($ground_width - $water_width) / 2;
                    $posY = ($water_height + $offset) * $set;
                    break;
                case 3://3为顶端居右
                    $posX = $ground_width - $water_width - $offset * $set;
                    $posY = ($water_height + $offset) * $set;
                    break;
                case 4://4为中部居左
                    $posX = $offset * $set;
                    $posY = ($ground_height - $water_height) / 2;
                    break;
                case 5://5为中部居中
                    $posX = ($ground_width - $water_width) / 2;
                    $posY = ($ground_height - $water_height) / 2;
                    break;
                case 6://6为中部居右
                    $posX = $ground_width - $water_width - $offset * $set;
                    $posY = ($ground_height - $water_height) / 2;
                    break;
                case 7://7为底端居左
                    $posX = $offset * $set;
                    $posY = $ground_height - $water_height;
                    break;
                case 8://8为底端居中
                    $posX = ($ground_width - $water_width) / 2;
                    $posY = $ground_height - $water_height;
                    break;
                case 9://9为底端居右
                    $posX = $ground_width - $water_width - $offset * $set;
                    $posY = $ground_height -$water_height;
                    break;
                default://随机
                    $posX = rand(0,($ground_width - $water_width));
                    $posY = rand(0,($ground_height - $water_height));
                    break;
            }

            if($isWaterImage === TRUE) {//图片水印
                imagealphablending($water_im,true); 
                imagealphablending($background_im,true); 


                imagecopy($background_im, $water_im, $posX, $posY, 0, 0, $water_width,$water_height);//拷贝水印到目标文件
            } else { //文字水印
                if( !empty($textColor) && (strlen($textColor)==7) ) {
                    $R = hexdec(substr($textColor,1,2));
                    $G = hexdec(substr($textColor,3,2));
                    $B = hexdec(substr($textColor,5));
                } else {
                    return "text color format mistake";
                }
                imagettftext($background_im, $textFont, 0, $posX, $posY, imagecolorallocate($background_im, $R, $G, $B), $fontfile , $waterText);
            }

            //生成水印后的图片
            @unlink($backgroundPath);
            switch($background_info[2])//取得背景图片的格式
            {
                case 1:
                    imagegif($background_im,$backgroundPath);
                    break;
                case 2:
                    imagejpeg($background_im,$backgroundPath);
                    break;
                case 3:
                    imagepng($background_im,$backgroundPath);
                    break;
                default:
                    die($errorMsg);
            }

            if(isset($water_im)) {
                imagedestroy($water_im);
            }

            imagedestroy($background_im);
        }

        /**
         * 图片验证码
         * 
         * @author zhouqi 2012-4-24 PM 02:02:07
         * @param string $session_name
         * @param int $num  位数  中文不用填写位数
         * @param int $model    模式（0：数字+字母，1：数字，2：字母，3：中文）
         * @param int $w    宽度
         * @param int $h    高度         
         * @param int $l    左
         * @param int $t    上
         */
        public function image_auth_code($session_name, $num = 4, $model = 0, $w = 100, $h = 25, $l = 0, $t = 0) {
            global $_site;
            mb_internal_encoding("gb2312");

            session_start();

            $model_ary = array(
            array(0,1,2,3,4,5,6,7,8,9),
            array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'),
            array('我的同城', '同城交友', '同城搜搜', '同城约会', '同城相册', '同城一网', '上下左右', '七七八八', '东方神娃')
            );

            $str = '';
            switch($model) {
                //数字加字母
                case 0:
                    $for_ary = array_merge($model_ary[0], $model_ary[1]);
                    for($i = 0; $i < $num; $i++) {
                        $str .= $for_ary[mt_rand(0, count($for_ary) - 1)];
                    }
                    break;
                    //数字
                case 1:
                    for($i = 0; $i < $num; $i++) {
                        $str .= mt_rand(0, 9);
                    }
                    break;
                    //字母
                case 2:
                    for($i = 0; $i < $num; $i++) {
                        $str .= $model_ary[1][mt_rand(0, 24)];
                    }
                    break;
                    //中文
                case 3:
                    $str = $model_ary[2][mt_rand(0, count($model_ary[2]) - 1)];
                    break;
            }

            //转换成大写
            $str = strtoupper($str);

            $_SESSION[$session_name] = $str;

            //创建画布
            $img_obj = imagecreate($w, $h);

            //字体颜色
            $fontcolor = imagecolorallocate($img_obj, 0, 0, 0);

            //背景色            
            $background = imagecolorallocate($img_obj, 255, 255, 255);

            //边框色
            $border = imagecolorallocate($img_obj, 0, 0, 0);            

            //从0,0点填充59*19的白色矩形区域
            imagefilledrectangle($img_obj, 0, 0, $w - 1, $h - 1, $background);

            //从0,0点绘制59*19的黑色矩形边框
            imagerectangle($img_obj, 0, 0, $w - 1, $h - 1, $border);

            //加入干扰象素 
            for($i = 0; $i < 200; $i++) {
                $rand_color = imagecolorallocate($img_obj, rand(0, 255), rand(0, 255), rand(0, 255));
                imagesetpixel($img_obj, rand()%100, rand()%50, $rand_color);                
            }

            $font = $_site->_root() . '/source/font/FZSTK.TTF';

            //字体
            imagettftext($img_obj, 15, 0, $l, $t + 18, $fontcolor, $font, $str);            

            header("Content-type: image/jpeg");
            imagejpeg($img_obj);            
            imagedestroy($img_obj);
            exit;
        }
        
        /*+--------------------------------Private--------------------------------------+*/
        
        /**
         * 生成裁剪略缩图
         * 
         * @param mixed $images_path 图片目录
         * @param mixed $photo 图片名称
         * @param mixed $top 裁剪的y
         * @param mixed $left 裁剪的x
         * @param mixed $width 选择裁剪区域宽
         * @param mixed $height 选择裁剪区域高
         * @param mixed $max_width 目标略缩图最宽
         * @param mixed $max_height 目标略缩图最高
         * @param mixed $thumb_postfix 缩略图后缀 默认_thumb 如果空 就是原图
         * @return mixed
         */
        private function image_make($images_path,$photo,$top,$left,$width,$height,$max_width,$max_height,$thumb_postfix='thumb_',$inc_array=array(), $thumb) {
            global $_site;
            $thumbs_path = $images_path;

            $quality = $inc_array['quality']?$inc_array['quality']:90; //生成质量
            $fill_margin = isset($inc_array['fill_margin'])?$inc_array['fill_margin']:true; //填充空白处
            $cut_center = isset($inc_array['cut_center'])?$inc_array['cut_center']:true; //居中裁剪            

            if(!($photo && is_numeric($top) && is_numeric($left) && is_numeric($width) && is_numeric($height) && is_numeric($max_height) && is_numeric($max_width))){
                return false;
            }

            if(!extension_loaded('gd')){
                return false;
            }            

            $source_file = $images_path ."/". $photo;

            //地址是否存在
            if(!is_dir($images_path)) {
                return false;
            }

            //文件是否存在
            if(!file_exists($source_file)) {
                return false;
            }

            //是否有权限
            if(!is_dir($thumbs_path)) {
                if(!mkdir($thumbs_path,0777,true)){
                    return false;
                }
            }

            //是否可写
            if(!is_writable($thumbs_path)){
                return false;
            }            

            //全路径
            $target_file = $thumbs_path ."/". $thumb;

            $info = getimagesize($source_file);

            if(!$info){
                return false;
            }

            //生成对应的图片
            switch($info[2]) {
                case IMAGETYPE_GIF:
                    if(!$source_image = imagecreatefromgif($source_file)){
                        return false;
                    }
                    break;
                case IMAGETYPE_PNG:
                    if(!$source_image = imagecreatefrompng($source_file)){
                        return false;
                    }
                    break;
                case IMAGETYPE_JPEG:
                    if(!$source_image = imagecreatefromjpeg($source_file)){
                        return false;
                    }
                    break;
                case IMAGETYPE_BMP:
                    include_once $_site->_root().'/source/lib/bmp.php';
                    $bmp_obj = new bmp();
                    if(!$source_image = $bmp_obj->imagecreatefrombmp($source_file)){
                        return false;
                    }
                    break;
                default:
                    return false;
                    break;
            }

            if($width < 1 || $height < 1){
                $width=$info[0];
                $height=$info[1];
            }               

            //计算最小框内图宽高 大图可以设定为目标宽高 但小图就必须以小图宽高为标准
            if($cut_center) {
                $min_width=min($max_width,$width);
                $min_height=min($max_width,$height);
            } else {
                $min_width=$max_width;
                $min_height=$max_height;
            }

            if($width > $height) {
                $dest_width = $min_width;
                $dest_height = round($min_width*$height/$width);
            } else {
                $dest_width = round($min_height*$width/$height);
                $dest_height = $min_height;
            }

            if($fill_margin) {
                $dest_width_temp= $max_width;
                $dest_height_temp=$max_height;
            } else {
                $dest_width_temp= $dest_width;
                $dest_height_temp=$dest_height;
            }

            //Calculate the position
            $dest_x=($dest_width_temp-$dest_width)/2;
            $dest_y=($dest_height_temp-$dest_height)/2;

            //we generate a new image object of the size calculated above, using PHP's GD functions
            if(!$dest_image = imagecreatetruecolor($dest_width_temp,$dest_height_temp)){
                return false;
            }

            //set the background color
            $back = imagecolorallocate($dest_image, 255, 255, 255);
            imagefill($dest_image,0,0,$back);

            //hack to keep transparency in gif and png
            if($info[2]==IMAGETYPE_GIF||$info[2]==IMAGETYPE_PNG){
                if($info[2]==IMAGETYPE_PNG){
                    imageAntiAlias($dest_image,true);
                }
                imagecolortransparent($dest_image, imagecolorallocatealpha($dest_image, 0, 0,0,127));
                imagealphablending($dest_image, false);
                imagesavealpha($dest_image, true);
            }

            if(!imagecopyresampled($dest_image, $source_image, $dest_x, $dest_y, $left, $top, $dest_width, $dest_height, max($width, $min_width), max($height, $min_height))){
                return false;
            }            

            switch($info[2]) {
                case IMAGETYPE_GIF:
                    if(!imagegif($dest_image, $target_file)){
                        return false;
                    }
                    break;
                case IMAGETYPE_PNG:
                    if(!imagepng($dest_image, $target_file, max(9 - floor($quality/10),0))){
                        return false;
                    }
                    break;
                case IMAGETYPE_JPEG:
                    if(!imagejpeg($dest_image, $target_file, $quality)){
                        return false;
                    }
                    break;
                case IMAGETYPE_BMP:
                    if(!imagejpeg($dest_image, $target_file, $quality)){
                        return false;
                    }
                    break;
            }
            imagedestroy($dest_image);
            imagedestroy($source_image);
            return true;
        }
    }
?>
